package team.tunan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import team.tunan.entity.User;
import team.tunan.entity.dto.UserDTO;
import team.tunan.mapper.UserMapper;
import team.tunan.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sqx
 * @since 2024-01-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDTO getUser(String account, String password) {
        System.out.println(account+ " " + password);
        User user = userMapper.getUsertoLogin(account, password);
        if(user == null){
            return new UserDTO(null,false);
        }
        return new UserDTO(user,true);
    }

    @Override
    public User getUserById(Integer id) {
        User user = userMapper.getUserById(id);
        return user;
    }

    @Override
    public List<User> getAllUser(HttpServletRequest request) {
        Map<String,Object> map = new HashMap();
        List<User> allUser = new ArrayList<>();
        User user = (User)request.getSession().getAttribute("user");
        Integer role = user.getRole();

        if(role == 1){
            allUser =  userMapper.getAllUser();
        }
        else{
            Integer id = user.getId();
            User userById = userMapper.getUserById(id);
            allUser.add(userById);
        }
        return allUser;
    }

    @Override
    public int add(User user) {
        System.out.println(user);
        int i = userMapper.insert(user);
        return i;
    }

    @Override
    public int update(User user) {
        int i = userMapper.updateUserByid(user);
        return i;
    }

    @Override
    public int del(Integer id) {
        int i = userMapper.deleteById(id);
        return i;
    }
}
